<template>
	<view>
		<!-- 顶部占位栏（适配状态栏 + 导航栏） -->
			<view :style="{ height: statusBarHeight + 'px' }"></view>
	<view class="container">
		<!-- 内容区域 -->
		<view>
			<!-- 玫瑰图 - 只在有数据时显示 -->
			<view class="charts-box" v-if="hasData">
				<qiun-data-charts type="rose" :opts="opts" :chartData="chartData" />
			</view>
			
			<!-- 无数据提示 -->
			<view class="empty-container" v-else>
				<!-- <image class="empty-image" src="/static/images/empty.png" mode="aspectFit"></image> -->
				<text class="empty-text">您还没有收藏任何非遗文化</text>
				<text class="empty-subtext">快去探索非遗文化的魅力吧~</text>
				<button class="explore-btn" @click="navigateToExplore">去探索</button>
			</view>
			
			<!-- 图鉴列表 -->
			<view class="book-grid" v-if="booksList.length > 0">
				<view 
					class="book-card" 
					v-for="item in booksList" 
					:key="item.categoryId"
					@click="toTenth(item.categoryId)"
				>
					<view class="cover-container">
						<image 
							class="book-cover" 
							:src="item.categoryImg" 
							mode="aspectFill"
							lazy-load="true"
						></image>
					</view>
					<text class="book-title">{{item.categoryName}}</text>
				</view>
			</view>
		</view>
	</view>
	</view>
</template>


<script>
	export default {
		data() {
			return {
				statusBarHeight: 0,
				id: '',
				allData: [],
				allCategoryData: [],
				Data: [],
				// 导航栏
				navHeight: '', //整体顶部导航栏的高度
				statusBarHeight: '', //状态栏高度
				width: '',
				// 列表
				booksList: [],
				tokenList: [],
				// 图表
				chartData: {},
				allList: [],
				marksBooksList: [],
				allBooksList: [],
				numberAll: {},
				thisbooksList: [],
				finalList: [],
				tokenList: [],
				categoryAll: [],
			    last: [], // 修改为数组类型,
		        hasData: false, // 新增：是否有数据的标志
				//您可以通过修改 config-ucharts.js 文件中下标为 ['rose'] 的节点来配置全局默认参数，如都是默认参数，此处可以不传 opts 。实际应用过程中 opts 只需传入与全局默认参数中不一致的【某一个属性】即可实现同类型的图表显示不同的样式，达到页面简洁的需求。
				opts: {
					color: ["#997066", "#BBAD95", "#B43636", "#A9837F", " #414C7B", " #872D29", "#84A690", "#C6CCE1",
						"#949DBC", "#B03232"
					],
					padding: [5, 5, 5, 5],
					enableScroll: false,
					legend: {
						show: true,
						position: "left",
						lineHeight: 25
					},
					extra: {
						rose: {
							type: "area",
							minRadius: 50,
							activeOpacity: 0.5,
							activeRadius: 10,
							offsetAngle: 0,
							labelWidth: 15,
							border: false,
							borderWidth: 2,
							borderColor: "#FFFFFF"
						}
					}
				}


			}
		},
		// 图表
	  onReady() {
	    this.getServerData();
	  },
	  onLoad() {
		  const systemInfo = uni.getSystemInfoSync();
		  		this.statusBarHeight = systemInfo.statusBarHeight || 0;
	    this.initSystemInfo();
	    this.initUserData();
	    this.loadInitialData();
	  },
	  onShow() {
	    this.refreshChartData();
	  },
  methods: {
    // 初始化系统信息
    initSystemInfo() {
      const { statusBarHeight, system } = uni.getSystemInfoSync();
      this.statusBarHeight = statusBarHeight;
      this.navHeight = statusBarHeight + (system.indexOf('iOS') > -1 ? 44 : 48);
      this.width = uni.getSystemInfoSync().windowWidth;
    },
    
    // 初始化用户数据
    initUserData() {
      const tokenData = uni.getStorageSync("storage_data") || {};
      this.id = tokenData.vuex_id || '';
    },
    
    // 加载初始数据
    async loadInitialData() {
      await this.loadCategoryList();
      await this.fetchMarksData();
    },
    
    // 加载分类列表
    async loadCategoryList() {
      try {
        const res = await uni.request({
          url: this.$BASE_URL.baseUrl + '/books/category/list'
        });
        this.booksList = res[1].data.rows;
      } catch (error) {
        console.error('加载分类列表失败:', error);
      }
    },
    
    // 获取标记数据
    async fetchMarksData() {
      if (!this.id) return;
      
      try {
        // 获取用户标记的项目
        const marksRes = await uni.request({
          url: this.$BASE_URL.baseUrl + '/books/marks/list',
          data: { marksUserId: this.id }
        });
        this.marksBooksList = marksRes[1].data.rows.map(e => e.marksAllId);
        
        // 获取所有项目
        const allRes = await uni.request({
          url: this.$BASE_URL.baseUrl + '/books/all/list'
        });
        this.allBooksList = allRes[1].data.rows.map(e => e.allId);
        this.allList = allRes[1].data.rows;
        
        this.processChartData();
      } catch (error) {
        console.error('获取标记数据失败:', error);
      }
    },
    
    // 处理图表数据
    processChartData() {
      // 找出用户标记的项目
      this.thisbooksList = this.marksBooksList.filter(id => 
        this.allBooksList.includes(id)
      );
      
      // 获取完整项目信息
      this.finalList = this.thisbooksList.map(id => 
        this.allList.find(item => item.allId === id)
      ).filter(Boolean);
      
      // 统计各类别的数量
      this.numberAll = {};
      this.finalList.forEach(element => {
        const ascriptionId = element.allAscriptionId;
        if (ascriptionId) {
          this.numberAll[ascriptionId] = (this.numberAll[ascriptionId] || 0) + 1;
        }
      });
      
      const nameMapping = {
        1: "传统舞蹈",
        2: "传统戏剧",
        3: "传统体育、游艺与杂技",
        4: "曲艺",
        5: "民俗",
        6: "传统音乐",
        7: "传统技艺",
        8: "传统美术",
        9: "民间文学",
        10: "传统医药"
      };
      
      // 确保所有类别都有初始值
      const keyValuePairs = {};
      for (let j = 1; j <= 10; j++) {
        keyValuePairs[j] = this.numberAll[j] || 0;
      }
      
      // 转换为图表需要的数据格式
        this.last = Object.entries(keyValuePairs)
          .filter(([key, value]) => value > 0)
          .map(([key, value]) => ({
            name: nameMapping[key] || `未知类别(${key})`,
            value: value
          }));
        
        // 更新数据状态标志
        this.hasData = this.last.length > 0;
      this.getServerData();
    },
        // 新增：跳转到探索页面
        navigateToExplore() {
          uni.switchTab({
            url: '/pages/books/books'
          });
        },
    // 刷新图表数据
    refreshChartData() {
      if (this.id) {
        this.fetchMarksData();
      }
    },
			//图片预览
			preview(i) {
				let imgsArray = [];
				imgsArray[0] = i;
				uni.previewImage({
					current: 0,
					urls: imgsArray
				});
			},
			toTenth(id) {
				uni.navigateTo({
					url: `/pages/mine/MyIllustrated/tenth/tenth?categoryId=${id}&userId=${this.id}`

				})
				// console.log(id)
			},
			//图表
			getServerData() {
				//模拟从服务器获取数据时的延时
				setTimeout(() => {
					//模拟服务器返回数据，如果数据格式和标准格式不同，需自行按下面的格式拼接
					let res = {
						series: [{
							data: this.last
						}]
					};
					this.chartData = JSON.parse(JSON.stringify(res));
				}, 500);
			},
			  getServerData() {
			      setTimeout(() => {
			        let res = {
			          series: [{
			            data: this.last
			          }]
			        };
			        this.chartData = JSON.parse(JSON.stringify(res));
			      }, 500);
			    }
			
	

		}

	}
</script>
<style lang="scss" scoped>
	.container {
		background-color: #f8f4e9;
		min-height: 100vh;
		padding: 20rpx;
	}
	
	/* 加载状态样式 */
	.loading-container {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		height: 60vh;
		
		.loading-text {
			margin-top: 20rpx;
			color: #7C191E;
			font-size: 28rpx;
		}
	}
	
	/* 玫瑰图样式 */
	.charts-box {
		width: 100%;
		height: 400rpx;
		background-color: #fff;
		border-radius: 20rpx;
		margin-bottom: 30rpx;
		box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.05);
		padding: 20rpx;
	}
		
		/* 无数据状态样式 */
		.empty-container {
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			padding: 60rpx 40rpx;
			background-color: #fff;
			border-radius: 20rpx;
			margin-bottom: 30rpx;
			box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.05);
		}
		
		.empty-image {
			width: 300rpx;
			height: 300rpx;
			margin-bottom: 30rpx;
		}
		
		.empty-text {
			font-size: 32rpx;
			color: #7C191E;
			font-weight: bold;
			margin-bottom: 15rpx;
		}
		
		.empty-subtext {
			font-size: 26rpx;
			color: #997066;
			margin-bottom: 40rpx;
		}
		
		.explore-btn {
			background-color: #B43636;
			color: #fff;
			border-radius: 50rpx;
			padding: 0 60rpx;
			font-size: 28rpx;
			height: 70rpx;
			line-height: 70rpx;
			box-shadow: 0 4rpx 12rpx rgba(180, 54, 54, 0.2);
		}
		
		/* 响应式调整 */
		@media (max-width: 600rpx) {
			.empty-container {
				padding: 40rpx 20rpx;
			}
			
			.empty-image {
				width: 250rpx;
				height: 250rpx;
			}
		}
	/* 图鉴网格布局 */
	.book-grid {
		display: grid;
		grid-template-columns: repeat(2, 1fr);
		gap: 30rpx;
	}
	
	/* 图鉴卡片 */
	.book-card {
		background-color: #fff;
		border-radius: 16rpx;
		overflow: hidden;
		box-shadow: 0 6rpx 18rpx rgba(0,0,0,0.05);
		transition: all 0.3s ease;
		
		&:active {
			transform: scale(0.98);
		}
	}
	
	/* 封面容器 */
	.cover-container {
		position: relative;
		width: 100%;
		aspect-ratio: 3/4;
		background-color: #f0e6d6;
		
		.book-cover {
			width: 100%;
			height: 100%;
			object-fit: cover;
		}
	}
	
	/* 书籍标题 */
	.book-title {
		display: block;
		padding: 20rpx;
		font-size: 28rpx;
		color: #3a2818;
		font-weight: bold;
		text-align: center;
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
	}
	
	/* 响应式设计 */
	@media (max-width: 600rpx) {
		.book-grid {
			grid-template-columns: 1fr;
			gap: 20rpx;
		}
		
		.charts-box {
			height: 350rpx;
		}
	}
</style>